package com.hnit.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hnit.web.bean.UserCoupons;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Param;

/**
 * 用户优惠券Mapper接口
 */
@Mapper
public interface UserCouponsMapper extends BaseMapper<UserCoupons> {

    // SQL语句作为@Select注解的参数
    @Select("SELECT * FROM user_coupons WHERE orderId = #{orderId}")
    UserCoupons selectByOrderId(@Param("orderId") Long orderId);


    /**
     * 将优惠券绑定到指定的订单ID
     *
     * @param userCouponId 用户优惠券ID
     * @param orderId      订单ID
     * @return 影响的行数
     */
    @Update("UPDATE user_coupons SET orderId = #{orderId} WHERE userCouponId = #{userCouponId}")
    int bindOrderToCoupon(@Param("userCouponId") Long userCouponId, @Param("orderId") Long orderId);

    /**
     * 统计用户某个优惠券的领取数量
     *
     * @param userId   用户ID
     * @param couponId 优惠券ID
     * @return 领取数量
     */
    @Select("SELECT COUNT(*) FROM user_coupons WHERE userId = #{userId} AND couponId = #{couponId}")
    Long countByUserIdAndCouponId(@Param("userId") Long userId, @Param("couponId") Long couponId);

    /**
     * 批量更新过期优惠券状态
     *
     * @return 更新数量
     */
    @Update("UPDATE user_coupons SET couponStatus = 3 " +
            "WHERE couponStatus = 1 AND expireTime < NOW()")
    int updateExpiredCoupons();

    /**
     * 统计用户各状态优惠券数量
     *
     * @param userId 用户ID
     * @param status 状态
     * @return 数量
     */
    @Select("SELECT COUNT(*) FROM user_coupons " +
            "WHERE userId = #{userId} AND couponStatus = #{status}")
    int countByUserIdAndStatus(@Param("userId") Long userId, @Param("status") Integer status);

    /**
     * 统计用户未过期的未使用优惠券数量
     *
     * @param userId 用户ID
     * @return 数量
     */
    @Select("SELECT COUNT(*) FROM user_coupons " +
            "WHERE userId = #{userId} AND couponStatus = 1 AND expireTime > NOW()")
    int countUnusedAndNotExpired(@Param("userId") Long userId);

    /**
     * 统计用户已过期的优惠券数量（包括状态为过期和时间过期但状态未更新的）
     *
     * @param userId 用户ID
     * @return 数量
     */
    @Select("SELECT COUNT(*) FROM user_coupons " +
            "WHERE userId = #{userId} AND (couponStatus = 3 OR (couponStatus = 1 AND expireTime < NOW()))")
    int countExpired(@Param("userId") Long userId);

    /**
     * 根据优惠券码查询用户优惠券
     *
     * @param userId     用户ID
     * @param couponCode 优惠券码
     * @return 用户优惠券
     */
    @Select("SELECT * FROM user_coupons " +
            "WHERE userId = #{userId} AND couponCode = #{couponCode}")
    UserCoupons selectByUserIdAndCouponCode(@Param("userId") Long userId, @Param("couponCode") String couponCode);
}
